<?php
/**
 * Created by PhpStorm.
 * User: yangsen
 * Date: 15/7/2
 * Time: 下午3:29
 */

class Oauth_Model extends CI_Model {

    public function __construct() {
        parent::__construct();
        $this->load->model('member');
    }

    public function forwardto_oauthbaseurl($url) {
        $oauthRedirect = base_url('oauth/oauthcode') . '?redirect=' . $url;
        redirect($this->getWechat()->wxOauthUserinfo($oauthRedirect));
    }

    public function oauthcheck() {
        $memberModel = new Member();
        $openid = $_SESSION['openid'];
        $redirect_url = '/';
        if(!empty($_GET['redirect'])) {
            $redirect_url = $_GET['redirect'];
        }

        if (empty($openid)) {
            $this->forwardto_oauthbaseurl($redirect_url);
        }

            $data['openid']=$openid;

            $userinfo = $memberModel->getUserInfoFromDb($openid);
            //var_dump($userinfo);
            if(!empty($userinfo)) {
                $tokenvalue = $userinfo['accesstoken'];
                $tokentime = $userinfo['tokenctime'];
                $refreshtoken = $userinfo['refreshtoken'];

                $now = time();
                if($tokentime+7200<$now) {
                    //token过期
                    if(!empty($refreshtoken)) {
                        $accesstoken = $this->getWechat()->wxOauthRefreshAccessToken($refreshtoken);

                        if(array_key_exists('errcode',$accesstoken)) {
                            $this->forwardto_oauthbaseurl($redirect_url);
                        } else {
                            $openid = $accesstoken['openid'];
                            $tokenvalue = $accesstoken['access_token'];
                            $refreshtoken = $accesstoken['refresh_token'];
                            $this->db->update('t_user', array(
                                'accesstoken' => $tokenvalue,
                                'refreshtoken' => $refreshtoken,
                                'tokenctime' => $now
                            ), array('openid' => $accesstoken['openid']));
                            $userinfo['accesstoken']=$tokenvalue;
                            $userinfo['refreshtoken']=$refreshtoken;
                            $userinfo['tokenctime']=$now;
                        }

                    } else {
                        $this->forwardto_oauthbaseurl($redirect_url);
                    }
                }
            } else {
                $this->forwardto_oauthbaseurl($redirect_url);
            }
            $_SESSION['userinfo'] = $userinfo;
    }

    public function getWechat() {
        $token = $this->config->item('wxtoken');
        $this->load->library('WeChat');
        $wechat = new WeChat($token);
        return $wechat;
    }
}